Global Error Handling
There are two pages for global error handling
- Root level
error.tsx. This file will handle errors on any component in the subtree through an error boundary. It does not catch any error in root levellayout.tsxandpage.tsx. - Root level
global-error.tsx. It behaves as its own standalone page (need its own html and body tags) and it is displayed as fallback when an error occurs inlayout.tsxorpage.tsx.
Next.js documentation: source
How to validate it
note
File global-error.tsx can only be tested in a production build. You need to run the app with pnpm run build && pnpm run start.
note
A utility component called Error was added to help testing this feature. You can find it under src/dev-utils/components/Error.
- Add the
Errorcomponent in the component tree where you want to trigger the error. - Run the app locally.
- You'll see a button Throw Error being rendered by the
Errorcomponent. If you press the button, it will cause an error in next.js causing it to show an error handler screen.
- Using the
Errorcomponent in the rootlayout.tsxor rootpage.tsxwill cause to displayglobal-error.tsxif you are running a production build. - Using the
Errorcomponent anywhere else in the subtree will cause an error that will call root levelerror.tsx(only if not caught by a more specificerror.tsxin the subtree).
Screenshots
Page error.tsx

Page global-error.tsx
